<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>从视频文件提取画面帧</title>
  <style>
    .img {
      width: 300px;
      aspect-ratio: 16/9;
    }
  </style>
</head>
<body>
  <input type="file" accept="video/*">

  <script>
    function drawVideo(vdo)  {
      return new Promise(resolve => {
        const cvs = document.createElement('canvas');
        const ctx = cvs.getContext('2d');
        cvs.height = vdo.videoWidth;
        cvs.height = vdo.videoHeight;
        ctx.drawImage(vdo, 0, 0, cvs.width, cvs.height)
        cvs.toBlob(blob => {
          resolve({
            blob,
            url: URL.createObjectURL(blob)
          })
        })
        // document.body.appendChild(cvs)
      })
    }

    function captureFrame(videoFile, time = 0) { 
      return new Promise(resolve => {
        const vdo = document.createElement('video');
        // const src = URL.createObjectURL(videoFile);
        // console.log(src)
        vdo.currentTime = time;
        vdo.autoplay = true;
        vdo.muted = true; 
        vdo.src = URL.createObjectURL(videoFile);
        // document.body.appendChild(vdo)
        // ps： 在这种情况下，视频没加载到页面上，就会定格在当前的那一帧上
        vdo.oncanplay = async () => {  // oncanplay 可以播放的时候
          const frame =  drawVideo(vdo, 5)
          console.log(frame)
          resolve(frame)
        }
        
      })
    }

    const inp = document.querySelector('input[type=file]');
    inp.onchange = async (e) => {
      const file = e.target.files[0];
      for(let i = 0; i < 10; i++) {
        const frame = await captureFrame(file, i + 1)
        createPreview(frame)
      }
      
    }

    function createPreview(frame) {
      const img = document.createElement('img');
      img.classList.add('img')
      img.src = frame.url;
      document.body.appendChild(img)
    }
  </script>
</body>
</html>